/*
 * scheduler.c
 * 
 * Copyright 2012 Laura <arual13@gmail.com>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 * 
 * 
 */


#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include "lib/scheduler.h"



/* 
 * -Ready Queue: Initialized threads from the GUI - printQueue(readyQueue);
 * -Wait Queue: When threads stops using CPU and still have work to do..
 * -Running Queue: the thread that is running 
 * -Finish Queue: threads that finished, they don't participate in the raffle'
 */
 
int runScheduler(configuration *config)
{
    
    /* Scheduler Queues */    
    threadQueue* readyQueue = initializeThreads(config);
    threadQueue* runQueue =  newQueue(config->threads_num);
    threadQueue* waitQueue = newQueue(config->threads_num);
    threadQueue* finishQueue =  newQueue(config->threads_num);
    threadQueue* sourceQueue = readyQueue;
    threadNode* winner = NULL;
    long int lotteryMax = 0; // Total number of tickets
    
    for (long int i = 0; i < config->threads_num; i++) {
        lotteryMax += config->tickets_num[i];
    }

    handler_active = 1;
    
    //printf("\nRunning in mode: %i \n", config->mode);
    
    /* While there are jobs to process*/
    while(readyQueue->head != NULL || waitQueue->head != NULL || runQueue->head != NULL) {
        
        long int number = getLotteryNum(lotteryMax);
        //printf("Lottery: %ld \n",number);
        
        /* Selects the thread */
        sourceQueue = readyQueue;
        winner = getNextProcess(sourceQueue,number);
        
        /* We can add a tag to the queue to know which one it corresponds*/
        if (winner == NULL) {
            sourceQueue = waitQueue;
            winner = getNextProcess(sourceQueue,number);
        }
        
        /* Probably the process already finished */
        if (winner != NULL) {
            
            //printf("Tread %ld wins! \n", winner->id);
            
            /* Sends the process to run, if they are in ready, send otherwise resubmit */
            moveElement(sourceQueue,runQueue,winner);
            
            
            /* TODO: PREEMPTIVE MODE*/
            if(config->mode == PREEMPTIVE) {
                
                units_to_complete = winner->work_units;
                
                /* If the thread is not finished, we can send it again */
                if(!winner->done){
                    setTimer(config->quantum/1000);
                    handler_active = 0;
                    pause_handler();
                    start_thread(winner);
                }
                handler_active = 1;
                disableTimer();
                //printf("The thread came back!\n");

            } 
            
            /* NON-PREEMPTIVE MODE*/
            else {
    
                long double percentage = config->quantum/(double)100;
                units_to_complete = percentage*winner->work_units;
                
                // When we have no units to complete
                if(winner->work_units == 0) {
                    units_to_complete = 0;
                // When we have less quantum than 1 work unit
                } else if ( units_to_complete == 0 ) {
                    units_to_complete = 1;
                // When we have less work than 1 quantum
                } else if ((winner->work_left - units_to_complete) < 0) {
                    units_to_complete = winner->work_left;
                }

                //printf("\nRunning thread %ld...\n", winner->id);
                pause_handler();
                start_thread(winner);
                //printf("The thread came back!\n");
                //pause_thread(winner); /* Pause the thread */
                
                /*Update the thread job!*/
                
                // No work done, no left
                if(winner->work_units == 0) {
                    winner->work_left = 0;
                // When we have less quantum than 1 work unit, we complete one
                } else if ( units_to_complete == 0 ) {
                    winner->work_left -= 1;
                // When we have less work than 1 quantum, all work done
                } else if ((winner->work_left - units_to_complete) < 0) {
                    winner->work_left = 0;
                // Everything else completed units_to_complete
                } else {
                    winner->work_left -= units_to_complete;
                }
                
                //winner->current_result += pi_result; /* TODO: Do something to the result*/
                //printf("Units Completed: %ld Result: %Lf\n",units_to_complete, winner->current_result);

            }
            
            //printf("Checking the result...\n");
            
            /* If there is still work to do, move it to waiting */
            /* TODO: Si hay trabajo todavia, va para wait*/
            if(!winner->done) {
                
                //printf("Still there are %ld units to complete...\n", winner->work_left);
               
                moveElement(runQueue,waitQueue,winner);
                
            }
            /* No work, then it already finished */
            else{
                //printf("Thread %ld finished...\n", winner->id);
                moveElement(runQueue,finishQueue,winner);
            }
        }
    }
    
    
    //printf("Done!\n");
      
    /* Release unsed memory 
    */
    freeQueue(readyQueue);
    freeQueue(waitQueue);
    freeQueue(runQueue);
    freeQueue(finishQueue);
    releaseMemory(config);
    return 0;
    
    
}

threadNode *getNextProcess(threadQueue* queue, int num)
{
    threadNode *node = getWinner(queue,num);

    return node;
        
}



long int getLotteryNum(long int limit)
{
    return rand()%limit; 
}


threadNode* getWinner(threadQueue* list, long int ticket)
{
    long int i;
    threadNode *node = NULL; 
    
    for(node = list->head; node; node = node->next) {
        
        long int tickets_num = node->tickets_num;
        
        for(i=0; i<tickets_num; i++)
        {
            if(ticket == node->tickets[i]) {
                return node;
            }
			/*printf("Looking Winner: %ld \n", node->id);*/
        }
    }
    
    return node;
        
}



int releaseMemory(configuration* config)
{
    free(config->tickets_num);
    free(config->work_units);
    free(config);
    
    return 0;
}


void catch_alarm(int sig) {
    
    //printf("Timer went off...\n");
    usleep(SECOND/2);
    
    if(!handler_active && !currentThread->done){
        pause_thread(currentThread);
        continue_handler();
    }else
    {
        //printf("\nHandler is active, nothing to do!\n");
    }
    
    
    
    
    
}

void setTimer(long int seconds){
    
    /* Set the alarm */
    if (signal(SIGALRM, catch_alarm) == SIG_ERR) {
        perror("Unable to catch SIGALRM");
        exit(1);
    }

    /* Set the values */
    it_val.it_interval.tv_sec =    1;
    it_val.it_interval.tv_usec =   1; 
    it_val.it_value.tv_sec =       seconds;
    it_val.it_value.tv_usec =      1; 
    
    /* Set the timer */
    if (setitimer(ITIMER_REAL, &it_val, NULL) == -1) {
            perror("error calling setitimer()");
			exit(1);
    }
}

void disableTimer()
{
    it_val.it_interval.tv_sec =  0;
    it_val.it_interval.tv_usec = 0;
    it_val.it_value.tv_usec =    0;
    it_val.it_value.tv_sec =     0;
    
    if (setitimer(ITIMER_REAL, &it_val, NULL) == -1) {
		perror("error calling setitimer(0) with 0 seconds");
		exit(1);
	}
	else
	{
		//printf("The timer has been stopped\n");
	}
       
    
}



